package com.qianye.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qianye.entity.Customer;
import com.qianye.entity.Role;
import com.qianye.mapper.CustomerMapper;
import com.qianye.service.DaemonService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private DaemonService daemonService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取唯一身份
        Customer customer = (Customer) principals.getPrimaryPrincipal();
        //从数据库中查出与该角色对应的角色信息
        Customer auth = daemonService.findAuth(customer.getCid());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<Role> roleList = auth.getRoleList();
        //对角色列表进行遍历，将角色添加进去
        for (Role role : roleList) {
            info.addRole(role.getRoleName());
        }
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名和密码令牌
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        //创造一个条件构造器
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("cusername",usernamePasswordToken.getUsername());
        //从数据库中查出一个用户
        Customer customer1 = customerMapper.selectOne(wrapper);
        if (customer1!=null){
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(customer1,customer1.getCpassword(),null,this.getName());
            return info;
        }
        return null;
    }
}
